<template>
  <div class="system-settings">
    <!-- 页面标题和操作栏 -->
    <div class="page-header">
      <div class="header-left">
        <h2>系统设置</h2>
        <p class="header-desc">系统参数配置与管理</p>
      </div>
      <div class="header-actions">
        <el-button type="success" icon="Check" @click="saveAllSettings" :loading="saving">
          保存所有设置
        </el-button>
        <el-button type="info" icon="Refresh" @click="refreshSettings">
          重置设置
        </el-button>
      </div>
    </div>

    <!-- 设置分类标签页 -->
    <el-tabs v-model="activeTab" type="border-card" class="settings-tabs">
      <!-- 基本设置 -->
      <el-tab-pane label="基本设置" name="basic">
        <el-card class="setting-card" shadow="never">
          <template #header>
            <span>系统基本配置</span>
          </template>
          <el-form :model="systemSettings" label-width="150px" class="setting-form">
            <el-form-item label="系统名称">
              <el-input v-model="systemSettings.systemName" placeholder="请输入系统名称" />
            </el-form-item>
            <el-form-item label="系统版本">
              <el-input v-model="systemSettings.version" placeholder="请输入系统版本" />
            </el-form-item>
            <el-form-item label="系统描述">
              <el-input 
                v-model="systemSettings.description" 
                type="textarea" 
                :rows="3"
                placeholder="请输入系统描述"
              />
            </el-form-item>
            <el-form-item label="维护模式">
              <div class="form-item-with-tip">
                <div class="form-tip">开启后普通用户无法登录，仅管理员可访问</div>
                <el-switch 
                  v-model="systemSettings.maintenanceMode" 
                  active-text="开启" 
                  inactive-text="关闭"
                />
              </div>
            </el-form-item>
            <el-form-item label="用户注册">
              <el-switch 
                v-model="systemSettings.allowRegistration" 
                active-text="允许" 
                inactive-text="禁止"
              />
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>

      <!-- 邮件设置 -->
      <el-tab-pane label="邮件设置" name="email">
        <el-card class="setting-card" shadow="never">
          <template #header>
            <span>邮件服务配置</span>
          </template>
          <el-form :model="emailSettings" label-width="150px" class="setting-form">
            <el-form-item label="SMTP服务器">
              <el-input v-model="emailSettings.smtpHost" placeholder="例：smtp.gmail.com" />
            </el-form-item>
            <el-form-item label="SMTP端口">
              <el-input-number v-model="emailSettings.smtpPort" :min="1" :max="65535" />
            </el-form-item>
            <el-form-item label="加密方式">
              <el-select v-model="emailSettings.encryption" placeholder="请选择加密方式">
                <el-option label="无" value="none" />
                <el-option label="SSL" value="ssl" />
                <el-option label="TLS" value="tls" />
              </el-select>
            </el-form-item>
            <el-form-item label="发件邮箱">
              <el-input v-model="emailSettings.fromEmail" placeholder="请输入发件邮箱" />
            </el-form-item>
            <el-form-item label="邮箱密码">
              <el-input 
                v-model="emailSettings.password" 
                type="password" 
                placeholder="请输入邮箱密码或授权码"
                show-password
              />
            </el-form-item>
            <el-form-item label="发件人名称">
              <el-input v-model="emailSettings.fromName" placeholder="请输入发件人名称" />
            </el-form-item>
            <el-form-item label="启用邮件通知">
              <el-switch v-model="emailSettings.enabled" />
            </el-form-item>
            <el-form-item label=" ">
              <el-button 
                type="primary" 
                icon="Promotion" 
                @click="testEmail" 
                :loading="emailTesting"
              >
                发送测试邮件
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>

      <!-- 通知设置 -->
      <el-tab-pane label="通知设置" name="notifications">
        <el-card class="setting-card" shadow="never">
          <template #header>
            <span>系统通知配置</span>
          </template>
          <el-form :model="notificationSettings" label-width="150px" class="setting-form">
            <el-form-item label="新订单通知">
              <el-switch v-model="notificationSettings.newOrderNotification" />
              <div class="form-tip">有新订单时发送通知</div>
            </el-form-item>
            <el-form-item label="订单状态更新">
              <el-switch v-model="notificationSettings.orderStatusUpdate" />
              <div class="form-tip">订单状态变更时发送通知</div>
            </el-form-item>
            <el-form-item label="系统维护通知">
              <el-switch v-model="notificationSettings.maintenanceNotification" />
              <div class="form-tip">系统维护时发送通知</div>
            </el-form-item>
            <el-form-item label="用户注册通知">
              <el-switch v-model="notificationSettings.userRegistrationNotification" />
              <div class="form-tip">新用户注册时发送通知</div>
            </el-form-item>
            <el-form-item label="通知接收邮箱">
              <el-input 
                v-model="notificationSettings.adminEmail" 
                placeholder="请输入管理员邮箱"
              />
            </el-form-item>
            <el-form-item label="通知发送时间">
              <el-time-picker
                v-model="notificationSettings.sendTime"
                format="HH:mm"
                value-format="HH:mm"
                placeholder="选择发送时间"
              />
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { settingsAPI } from '@/api/settings'

// 组件名称
defineOptions({
  name: 'SystemSettings'
})

// 添加页面加载测试
console.log('SystemSettings page loaded')

// 响应式数据
const activeTab = ref('basic')
const saving = ref(false)
const emailTesting = ref(false)

// 系统基本设置
const systemSettings = reactive({
  systemName: '资源回收管理平台',
  version: '1.0.0',
  description: '智能化资源回收管理系统',
  maintenanceMode: false,
  allowRegistration: true
})

// 邮件设置
const emailSettings = reactive({
  smtpHost: '',
  smtpPort: 587,
  encryption: 'tls',
  fromEmail: '',
  password: '',
  fromName: '资源回收平台',
  enabled: false
})

// 通知设置
const notificationSettings = reactive({
  newOrderNotification: true,
  orderStatusUpdate: true,
  maintenanceNotification: true,
  userRegistrationNotification: false,
  adminEmail: '',
  sendTime: '09:00'
})

// 数据获取函数
const fetchSystemSettings = async () => {
  try {
    const response = await settingsAPI.getSystemSettings()
    Object.assign(systemSettings, response)
  } catch (error) {
    console.error('获取系统设置失败:', error)
  }
}

const fetchEmailSettings = async () => {
  try {
    const response = await settingsAPI.getEmailSettings()
    Object.assign(emailSettings, response)
  } catch (error) {
    console.error('获取邮件设置失败:', error)
  }
}

const fetchNotificationSettings = async () => {
  try {
    const response = await settingsAPI.getNotificationSettings()
    Object.assign(notificationSettings, response)
  } catch (error) {
    console.error('获取通知设置失败:', error)
  }
}

// 事件处理函数
const saveAllSettings = async () => {
  saving.value = true
  try {
    await Promise.all([
      settingsAPI.updateSystemSettings(systemSettings),
      settingsAPI.updateEmailSettings(emailSettings),
      settingsAPI.updateNotificationSettings(notificationSettings)
    ])
    ElMessage.success('所有设置保存成功')
  } catch (error) {
    console.error('保存设置失败:', error)
    ElMessage.error('保存设置失败')
  } finally {
    saving.value = false
  }
}

const refreshSettings = () => {
  fetchSystemSettings()
  fetchEmailSettings()
  fetchNotificationSettings()
  ElMessage.success('设置已重置')
}

const testEmail = async () => {
  // 确认操作
  ElMessageBox.confirm(
    '测试邮件将发送给系统中所有用户（管理员除外），是否继续？',
    '确认测试',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    emailTesting.value = true
    try {
      await settingsAPI.testEmailSettings(emailSettings)
      ElMessage.success('测试邮件已发送给所有用户，请检查收件箱')
    } catch (error) {
      console.error('邮件测试失败:', error)
      ElMessage.error(error.message || '邮件测试失败')
    } finally {
      emailTesting.value = false
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 生命周期
onMounted(() => {
  console.log('SystemSettings component mounted')
  fetchSystemSettings()
  fetchEmailSettings()
  fetchNotificationSettings()
})
</script>

<style scoped>
.system-settings {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
}

.header-left h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.header-desc {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.settings-tabs {
  border-radius: 12px;
}

.setting-card {
  border-radius: 12px;
  border: none;
  box-shadow: none;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 500;
}

.setting-form {
  max-width: 600px;
}

.form-item-with-tip {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-tip {
  color: #6b7280;
  font-size: 12px;
  margin-bottom: 8px;
  line-height: 1.5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-start;
  }
  
  .setting-form {
    max-width: 100%;
  }
}
</style>